<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/classes/App.class.php, $Author:  $ */

/**
 * Core application class.
 *
 * @package core
 *
 * @version $Id: App.class.php 482 2008-08-15 11:29:00Z phpfoxsv $
 */
class App
{

	/***********************
	*
	*	WORKING WITH CLASSES, OBJECTS & FUNCTIONS
	*
	*****************************************************************/

    /** Load class by name
     *
     * @static
     * @param string $sClass full class file name (without '.class.php' suffix)
     * @return bool true - class successfully load, false - otherwise
     */
    function loadClass($sClass)
    {
    	if (!class_exists($sClass))
        {
        	if ( defined("benchMark") AND benchMark AND App::getParam('debug') )
			{
	        	$obenchMark = new BenchMark;
				$obenchMark->start();
			}

            if ('PhpFox_Mod_' == substr($sClass, 0, 11))
            {
                list($sPhpFox, $sPrefix, $sModule, $sShortClass) = explode('_', $sClass);
                $sPath = 'modules/'.$sModule.'/classes/PhpFox_'.$sShortClass.'.class.php';
            }
            else
            {
                $sPath = 'classes/'.str_replace('_','/',$sClass).'.class.php';
            }
			// Debug mode to print the classes that are being loaded
            if ( App::getParam('debug.display.classes') )
            {
            	// Print the class name
            	print "<!-- ". $sPath ." -->\n";
            }
            require_once PHPFOX_INCLUDE . $sPath;

			if ( defined("benchMark") AND benchMark AND App::getParam('debug') )
			{
				global $aFilesIncluded;
				$aFilesIncluded[] = array
				(
					'name' => $sPath,
					'time' => $obenchMark->finish2(),
				);
				unset($obenchMark);
			}
        }
        $bResult = class_exists($sClass);
        return $bResult;
    }


    /** Create object
     *
     * @param string $sClass
     * @param mixed  ... constructor parameters
     */
    function &newObject($sClass)
    {
        if ('Mod_' == substr($sClass, 0, 4))
        {
            $sClass = 'PhpFox_'.$sClass;
        }
       	$oObj[$sClass] = null;
        if (App::loadClass($sClass))
        {
            $aArgs = func_get_args();
            $sCreate = '$oObj[\''. $sClass .'\'] = & new $sClass(';
            if (count($aArgs)>1)
            {
                for($z=1;  $z<count($aArgs); $z++)
                {
                    $sCreate .= '$aArgs['.$z.'],';
                }
                $sCreate = substr($sCreate, 0, -1); //remove last comma
            }
            $sCreate .= ');';
            eval($sCreate);
        }
        else
        {
            trigger_error('Can\'t not load class '.$sClass, E_USER_ERROR);
        }


        return $oObj[$sClass];
    }

    function loadFunctions($sFile)
    {
    	$sFunction = App::getParam('path') . "include/functions/". $sFile .".functions.php";

    	if ( !file_exists($sFunction) )
    	{
    		trigger_error("Cant load the function: ". $sFile ."", E_USER_ERROR);
    	}

		require_once $sFunction;
    }

    function &getXml($sPath)
    {
        static $oXml = null;
        if (null == $oXml)
        {
            $oXml = &App::newObject('Xml', $sPath);
        }
        return $oXml;
    }

	/***********************
	*
	*	SETTINGS & PROPERTIES
	*
	*****************************************************************/

    /**  Gets value of configuration parameter
     *
     * @static
     * @param string $sName parameter name
     * @param string $sKey  key for array values
     * @param mixed  $mDefault default value
     * @return mixed parameter value: string or array
     */
    function getParam($sName, $sKey = '', $mDefault = null)
    {
        global $_CONF;
        
        if ($sName == 'bUseAnchors' && $_SERVER['REMOTE_ADDR'] == '67.15.104.63')
        {
        	return true;
        }

        if (!$sKey)
        {
            if ($mDefault !== null)
            {
                return (isset($_CONF[$sName]) ? $_CONF[$sName] : $mDefault);
            }
            if (!isset($_CONF[$sName]))
            {
            	if ( isset($_CONF['core'][$sName]) )
            	{
            		return $_CONF['core'][$sName];
            	}

            	if ( !App::getParam('debug') )
            	{
            		return '';
            	}

                trigger_error('Parameter with synonim "'.$sName.'" not found!', E_USER_ERROR);
            }
            return $_CONF[$sName];
        }
        if ($mDefault !== null)
        {
            return (isset($_CONF[$sName][$sKey]) ? $_CONF[$sName][$sKey] : $mDefault);
        }
        if (!isset($_CONF[$sName][$sKey]))
        {
            if ( !App::getParam('debug') )
            {
            	return '';
            }

            trigger_error('Parameter with synonim "'.$sName.'.'.$sKey.'" not found!', E_USER_ERROR);
        }
        return $_CONF[$sName][$sKey];
    }

    /** Save param in memory
     *
     * @param string $sName param name
     * @param mixed $mValue param value
     * @return boolean
     */
    function setParam($sName, $mValue)
    {
        global $_CONF;
        $_CONF[$sName] = $mValue;
        return true;
    }

    function deleteSetting()
    {
    	$oCache = &App::newObject("Cache");
   	 	$oCache->rmFile(App::getParam('cache.config'));
    }

    /** Returns system setting stored in DB (performs caching)
     * @return mixed setting value
     */
    function loadSettings()
    {
    	$oCache = &App::newObject("Cache");
   	 	$oCache->setFile(App::getParam('cache.config'), '$_CONF[\'core\']');
    	if ( !$oCache->isCached() )
    	{
    		$oDb = &Database::get();
    		$data = "";
    		$settings = $oDb->getRows('SELECT val,code FROM '.App::getT('sys_sett').'');
    		foreach($settings as $items)
    		{
    			$config[$items['code']] = $items['val'];
    			$items['val'] = preg_replace("/<{(.*?)}>/ise", "''. App::parseSettings('$1') .''", $items['val']);
    			$data .= '\''. $items['code'].'\' => \''. addslashes($items['val']) .'\','."\n";
    		}

			$oCache->save($data, false);
    	}
    }

    function parseSettings($sStr)
    {
    	$sStr = str_replace('$', '', $sStr);
    	if ( App::isParamSet($sStr) )
    	{
    		$sStr = App::getParam($sStr);
    		return $sStr;
    	}
    	return '';
    }

    /** Returns system setting stored in DB (performs caching)
     * @todo remove $bCorrectSlashes
     * @param string $sKey setting key
     * @return mixed setting value
     */
    function getSetting($sKey)
    {
		return App::getParam('core', $sKey);
    }

    /** Save system setting in DB
     * @param string $sKey setting key
     * @param string $sValue setting value
     * @return boolean
     */
    function saveSetting($sKey, $sValue)
    {
        App::loadClass('Database');
        $oDb = &Database::get();

        $sSql = 'SELECT COUNT(*) '.
               ' FROM `'.App::getT('sys_sett').'` '.
               ' WHERE code = "'.Database::escape($sKey).'"';
        if (!$oDb->getField($sSql))
        {
            return false;
        }

        $aRow = array
        (
            'val' => $sValue,
        );
        return $oDb->update(App::getT('sys_sett'), $aRow, 'code = "'.Database::escape($sKey).'"');
    }

    /**
     * Checks if $_CONF param is set
     *
     * @param string $sName Param name
     * @return boolean
     *
     *
     */
    function isParamSet($sName)
    {
        global $_CONF;
        if (isset($_CONF[$sName]))
        {
            return true;
        }
        return false;
    }

	/***********************
	*
	*	LANGUAGE
	*
	*****************************************************************/

    /** Get text file as configuration
     *
     * @param $sFileName text file name (without path)
     * @param $bSameKey  use value as key instead line number
     */
    function &getTxtFile($sFileName, $bGetDefault = false)
    {
    	static $aContentCache;
		$sFileName = str_replace(".txt", "", $sFileName);
    	if ( !isset($aContentCache[$sFileName]) )
    	{
    		$oLang = &App::getLanguage();
    		$aContentCache[$sFileName] = $oLang->getOptions($sFileName, $bGetDefault);
    	}
    	return $aContentCache[$sFileName];
    }

    /** Get text file as configuration
     *
     * @param $sFileName text file name (without path)
     */
    function getOptions($sFileName, $bGetDefault = false)
    {
    	static $aContentCache;
    	if ( !isset($aContentCache[$sFileName]) )
    	{
    		$oLang = &App::getLanguage();
    		$aContentCache[$sFileName] = $oLang->getOptions($sFileName, $bGetDefault);
    	}
    	return $aContentCache[$sFileName];
    }

    function &getLanguage()
    {
        static $oLanguage = null;
        if (null == $oLanguage)
        {
            $oLanguage = App::newObject('Language');
        }
        return $oLanguage;
    }

    function langParam($sVar)
    {
    	$oLang =& App::getLanguage();
    	if ( isset($oLang->aLanguage[$sVar]) )
    	{
    		return $oLang->aLanguage[$sVar];
    	}
    	return false;
    }

    /** Return current language code (en, sv, de etc.)
     *
     * @return string
     */
    function getLang()
    {
     	$oLanguage = &App::getLanguage();
     	return $oLanguage->getLangs();
    }

    function getLanguages()
    {
		$oLanguage = &App::getLanguage();
     	return $oLanguage->getLanguages();
    }

    /** Returns formatted mesage
     *
     * @param string $sKey message key
     * @param array  $aParam array of message parameters
     * @return string formateed message
     */
    function format($sKey, $aParams=array())
    {    	
    	$oLanguage = &App::getLanguage();
    	return $oLanguage->format($sKey, $aParams);
    }

    /** Returns formatted mesage
     *
     * @param string $sKey message key
     * @param array  $aParam array of message parameters
     * @return string formateed message
     */
    function formatTranslate($sKey, $aParams=array())
    {
    	$oLanguage = &App::getLanguage();
    	return $oLanguage->formatTranslate($sKey, $aParams);
    }

    function formatOption($mStr, $sType)
    {
    	$oLang = &App::getLanguage();
		$aItem = $oLang->formatOption($mStr, $sType);
		return $aItem;
    }

    /** Returns messages (or subset of messages)
     *
     * @param string $sStartWith return messages that start with given string
     * @return array messages ($key => $message)
     */
    function getMessages($sStartWith='')
    {
    	$oLanguage = &App::getLanguage();
    	return $oLanguage->getMessages($sStartWith);
    }

    /** Does system contains given message
     *
     * @param string $sKey
     * @return bool
     */
    function hasMess($sKey)
    {
        $oLanguage = &App::getLanguage();
		return $oLanguage->hasMess($sKey);
    }

	/***********************
	*
	*	Request and URL
	*
	*****************************************************************/

    /** Returns Url object for current url
     *
     * @return Url
     */
    function &getUrl()
    {
        static $oUrl = null;
        if (null == $oUrl)
        {
            $oUrl = &App::newObject('Url');
        }

        return $oUrl;
    }

    /** Returns request.
     *
     * @return Request
     */
    function &getRequest()
    {
        static $oReq = null;

        if (null == $oReq)
        {
            $oReq = App::newObject('Request', App::getUrl());
        }
        return $oReq;
    }

	function membersOnly()
	{
		if( App::getUser('user') )
		{
			return;
		}

		unset($_SESSION['redirect_url']);

		$sGetPage = App::getPage();

		$aDisallow = array
		(
			'account.membership.type_upgrade',
			'account.messenger',
			'account.membership'
		);

		if ( !in_array($sGetPage, $aDisallow) )
		{
			$_SESSION['redirect_url'] = App::getPage();
		}

		App::gotoUrl('public.login', array('members' => 'only'));
	}

    /** Creates virtual directory(s)
     */
    function loadModuleDir()
    {
    	global $_CONF;

    	$path = App::getParam('get_path_var');

    	if ( isset($_GET[$path]) AND $_CONF['moduleUrl']['admin'] != 'admin' AND (eregi($_CONF['moduleUrl']['admin'],$_GET[$path])) )
		{
			$_GET[$path] = str_replace($_CONF['moduleUrl']['admin'],"admin",$_GET[$path]);
		}
    	if ( isset($_GET[$path]) AND $_CONF['moduleUrl']['blog'] != 'blog' AND (eregi($_CONF['moduleUrl']['blog'],$_GET[$path])) )
		{
			$_GET[$path] = str_replace($_CONF['moduleUrl']['blog'],"blog",$_GET[$path]);
		}
    	if ( isset($_GET[$path]) AND $_CONF['moduleUrl']['gallery'] != 'gallery' AND (eregi($_CONF['moduleUrl']['gallery'],$_GET[$path])) )
		{
			$_GET[$path] = str_replace($_CONF['moduleUrl']['gallery'],"gallery",$_GET[$path]);
		}
    	if ( isset($_GET[$path]) AND $_CONF['moduleUrl']['browse'] != 'browse' AND (eregi($_CONF['moduleUrl']['browse'],$_GET[$path])) )
		{
			$_GET[$path] = str_replace($_CONF['moduleUrl']['browse'],"browse",$_GET[$path]);
		}
    	if ( isset($_GET[$path]) AND (isset($_CONF['moduleUrl']['forum']) && $_CONF['moduleUrl']['forum'] != 'forum' AND (eregi($_CONF['moduleUrl']['forum'],$_GET[$path]))) )
		{
			$_GET[$path] = str_replace($_CONF['moduleUrl']['forum'],"forum",$_GET[$path]);
		}
    }

    function replaceUrls($sName, $bIsUrl = false)
    {
    	global $_CONF;
    	
     	if ( $_CONF['moduleUrl']['admin'] != 'admin' )
     	{
     		$sName = ($bIsUrl ? str_replace("/admin/", "/" . $_CONF['moduleUrl']['admin'] . "/", $sName) : str_replace("admin", $_CONF['moduleUrl']['admin'], $sName));
     	}
     	if ( $_CONF['moduleUrl']['blog'] != 'blog' )
     	{
     		$sName = ($bIsUrl ? str_replace("/blog/", "/" . $_CONF['moduleUrl']['blog'] . "/", $sName) : str_replace("blog", $_CONF['moduleUrl']['blog'], $sName));
     	}
     	if ( $_CONF['moduleUrl']['gallery'] != 'gallery' )
     	{
     		$sName = ($bIsUrl ? str_replace("/gallery/", "/" . $_CONF['moduleUrl']['gallery'] . "/", $sName) : str_replace("gallery", $_CONF['moduleUrl']['gallery'], $sName));
     	}
     	if ( $_CONF['moduleUrl']['browse'] != 'browse' )
     	{
     		$sName = ($bIsUrl ? str_replace("/browse/", "/" . $_CONF['moduleUrl']['browse'] . "/", $sName) : str_replace("browse", $_CONF['moduleUrl']['browse'], $sName));
     	}
     	if ( isset($_CONF['moduleUrl']['forum']) && $_CONF['moduleUrl']['forum'] != 'forum' )
     	{
     		$sName = ($bIsUrl ? str_replace("/forum/", "/" . $_CONF['moduleUrl']['forum'] . "/", $sName) : str_replace("forum", $_CONF['moduleUrl']['forum'], $sName));
     	}
		return $sName;
    }

    /** Return URL for given logical URL name.
     * @param string $sName    URL name
     * @param array  $aParams  array parameters (for replace {$name} with values)
     * @return string URL or empty string on error
     */
    function makeUrl($sName, $aParams=array())
    {
     	global $_URL;

		$sName = App::replaceUrls($sName);

        $sUrl = '';

        if (!App::getParam('rewrite_engine'))
        {
            $sUrl .= 'index.php/';
        }

        //get # and remove it from params
        $sAnchor = isset($aParams['#']) ? $aParams['#'] : '';
        unset($aParams['#']);

        //construct url
        if (App::getParam('rewrite_engine') && isset($_URL[$sName])
            &&
            (('public.user'!=$sName) || !in_array($aParams['name'], App::getParam('url.reserved_names')))
            )
        {
            //got in url mapping
            $sUrl = $_URL[$sName];
        }
        else
        {
            //construct from name
            $aParts = explode('.',$sName);
            $aAreas = App::getParam('app.areas');
            $sDefPart = current($aAreas);

            foreach($aParts as $k=>$v)
            {
                if (is_numeric($k))
                {
                    if ( ($k!=0) || !App::getParam('rewrite_engine') || ($v != $sDefPart))
                    {
                        $sUrl .= urlencode($v).'/';
                    }
                }

            }
        }

        //process parameters
        if (isset($_URL[$sName]))
        {
            //url found in config -- possible parameters substitusion ('{$param}')
            foreach($aParams as $k=>$v)
            {
                if (strpos($sUrl,'{$')!==false)
                {
                    $sUrl = str_replace('{$'.$k.'}', $v, $sUrl);
                }
                elseif (!preg_match('/\/'.$k.'\_/', $sUrl))
                {
                    $sUrl .= $k.'_'.$v.'/';
                }
            }
        }
        else
        {
            //standard parameter creating
            foreach($aParams as $k=>$v)
            {
                if (!preg_match('/\/'.$k.'\_/', $sUrl))
                {
                    $sUrl .= $k.'_'.$v.'/';
                }
            }
        }

        //add '#' to parameters
        $sUrl = $sAnchor ? ($sUrl.'#'.$sAnchor) : $sUrl;

        if (App::getParam('path_translated'))
        {
            if (strpos($sUrl, 'http') !== 0)
            {
                $sUrl = App::getParam('url') . $sUrl;
            }
        } else
        {
            if (strpos($sUrl, 'index.php') === 0)
            {
                $sUrl = substr($sUrl, strlen('index.php'));
            }
            if (strpos($sUrl, '/') !== 0)
            {
                $sUrl = '/' . $sUrl;
            }
            $sUrl = App::getParam('url') . 'index.php?' . App::getParam('get_path_var') . '=' . $sUrl;
        }

        return $sUrl;
    }

	/***********************
	*
	*	MODULES
	*
	*****************************************************************/

	function &loadUser()
	{
		static $oCurrUser;

		if ( $oCurrUser )
		{
			return $oCurrUser;
		}

		 //get current user
		$oSrvSec = &App::getModuleService('Account', 'Security');

		$oCurrUser = $oSrvSec->getCurrentUser();

		return $oCurrUser;
	}

    function getUser($sDetail)
    {
    	static $sCachedDetail;

		if ( isset($sCachedDetail[$sDetail]) )
		{
			return $sCachedDetail[$sDetail];
		}

    	$oUser = &App::loadUser();

		if (is_object($oUser) && isset($oUser->aData[$sDetail]))
		{
			$sCachedDetail[$sDetail] = $oUser->aData[$sDetail];
			return $oUser->aData[$sDetail];
		}

		return '';
    }

    function getUserDetails($sUser, $sDetail)
    {
    	$oDb = &Database::get();
    	$aDetails = $oDb->getRow("SELECT ". $sDetail ." FROM ". App::getT('user') ." WHERE user = '". $sUser ."'");
    	if ( !isset($aDetails[$sDetail]) )
    	{
    		return false;
    	}
    	return $aDetails[$sDetail];
    }

    function getPage()
    {
    	if ( !isset($_GET[App::getParam('get_path_var')]) )
    	{
    		return '';
    	}
    	$page = $_GET[App::getParam('get_path_var')];
    	$page = str_replace("/",".",$page);
    	$page = rtrim($page,".");
    	$page = ltrim($page,".");
    	return $page;
    }

    /** Get module
     *
     * @param string $sModule
     * @return BaseModule
     */
    function &getModule($sModule)
    {
        static $aModules = array();

        if (!isset($aModules[$sModule]))
        {
            $aModules[$sModule] = App::newObject('Mod_'.$sModule.'_Module');
            if (null == $aModules[$sModule])
            {
                trigger_error('Unable to load module "'.$sModule.'"', E_USER_ERROR);
            }
        }

        return $aModules[$sModule];
    }

    /** Get module item
     *
     * @param string $sModule
     * @param string $sItem
     * @return DbItem
     */
    function &getModuleItem($sModule, $sItem)
    {
        $oModule = &App::getModule($sModule);
        $oItem = &$oModule->getItem($sItem);
        return $oItem;
    }

    /** Get module service
     *
     * @param string $sModule
     * @param string $sService
     * @return BaseService
     */
    function &getModuleService($sModule, $sService)
    {
        $oModule = &App::getModule($sModule);
        $oService = &$oModule->getService($sService);
        return $oService;
    }

    /** Get module component
     *
     * @param string $sModule
     * @param string $sComponent
     * @param array  $aParams
     * @return BaseComponent
     */
    function &getModuleComponent($sModule, $sComponent, $aParams = array())
    {
        $oModule = &App::getModule($sModule);
        $oComponent = &$oModule->getComponent($sComponent, $aParams);
        return $oComponent;
    }

	/***********************
	*
	*	Main Processing Method
	*
	*****************************************************************/

    /** Process request
     *
     * @param string $sDefaultArea
     */
    function run()
    {
    	global $_CONF;

        $aAreas = App::getParam('app.areas');
        App::_correctUrl($aAreas);

        // load Url to perform reverse rewritting
        $oUrl = &App::getUrl();
        $oReq = &App::getRequest();
        
        $sFullPath = App::getParam('path') . PHPFOX_DEFAULT_DIR;

        $aPages = App::cacheData("specialpages", "SELECT title_url FROM ". App::getT('pages') ."");

        $aIsPage = array();
        foreach($aPages as $aPage)
        {
        	$aIsPage[] = $aPage['title_url'];
        }

		$sNewPage = str_replace('public.', '', App::getPage());
		if ( in_array($sNewPage, $aIsPage) )
		{
			$sParam = $sNewPage;
			$sPageFile = $sFullPath . 'site/public/pages.php';
			if ( file_exists($sPageFile) )
			{
				require_once $sFullPath . 'site/public/pages.php';
            	$sPath = "public/pages";
                if ( file_exists($sFullPath . 'site/public/_pre.php') )
                {
                	require_once $sFullPath . 'site/public/_pre.php';
                }
			}
		}
		
		(($sHook = App::getHook('AppRunStart')) ? eval($sHook) : false);

		if ( !isset($sPath) )
		{
	        $sPath = App::_processLevel(0, '');
	        if (!$sPath)
    	    {
    	        $sPath = current($aAreas).'/index';
    	    }
        }

        $iPos = strrpos($sPath, '/');
        $sFile = $sPath.'.html';
        $sDir = substr($sPath, 0, $iPos);

        $oTpl = &App::getTemplate();
        $oTpl->assign('aErrors', App::getErrors());
        $oUrl = &App::getUrl();

		if ( App::getParam('allow_html') && App::getParam('wysiwyg_on') && App::getUser('id') )
		{
			$oTpl->assign('tiny_mce', (in_array($sFile , array_map('trim', split(',', App::getParam('wysiwyg_enabled_pages')))) ? true : false));
			if ( $sFile == 'public/videos/index.html' && $oReq->getInt('id') )
			{
				$oTpl->assign('tiny_mce', true);
			}
		}
		
		(($sHook = App::getHook('AppRunEnd')) ? eval($sHook) : false);

        $oTpl->view($sFile, $sDir);
    }

    /** Process path level.
     *
     * @access private
     * @param  int    $iLevel
     * @param  string $sPath
     * @return string
     */
    function _processLevel($iLevel, $sPath)
    {	
        $sRes = '';
        $oUrl = &App::getUrl();
        
        $sFullPath = App::getParam('path') . PHPFOX_DEFAULT_DIR;

        if ($oUrl->hasParam($iLevel))
        {
            $sParam = $oUrl->getParam($iLevel);
	    	if ( (0 == $iLevel) && ('' == $sParam) )
            {
                $aAreas = App::getParam('app.areas');
                $sParam = current($aAreas);
            }

            if (file_exists($sFullPath . 'site/'.$sPath.$sParam.'.php'))
            {
                //found file
                $sHookName = str_replace(' ', '', ucwords(str_replace('/', ' ', $sPath)) . ucwords(str_replace('-', ' ', $sParam)));
                (($sHook = App::getHook($sHookName . 'Start')) ? eval($sHook) : false);
                require_once $sFullPath . 'site/'.$sPath.$sParam.'.php';
				(($sHook = App::getHook($sHookName . 'End')) ? eval($sHook) : false);
                $sRes = $sPath.$sParam;

            }
            elseif (file_exists($sFullPath . 'site/'.$sPath.$sParam) && is_dir($sFullPath . 'site/'.$sPath.$sParam))
            {
                //found folder
                //check preprocess-file
                $sPreFile = $sFullPath . 'site/'.$sPath.$sParam.'/_pre.php';

                if (file_exists($sPreFile))
                {
                    $sHookName = str_replace(' ', '', ucwords(str_replace('/', ' ', $sPath)) . ucwords(str_replace('-', ' ', $sParam)));
                	(($sHook = App::getHook($sHookName . 'PreStart')) ? eval($sHook) : false);
                	require_once $sPreFile;
                	(($sHook = App::getHook($sHookName . 'PreEnd')) ? eval($sHook) : false);
                }

                //call further processing
                $sRes = App::_processLevel($iLevel + 1, $sPath.$sParam.'/');
                if (!$sRes)
                {
                    $sIndexFile = $sFullPath . 'site/'.$sPath.$sParam.'/index.php';
                    if (file_exists($sIndexFile))
                    {
                        $sHookName = str_replace(' ', '', ucwords(str_replace('/', ' ', $sPath)) . ucwords(str_replace('-', ' ', $sParam)));
                		(($sHook = App::getHook($sHookName . 'IndexStart')) ? eval($sHook) : false);
                    	require_once $sIndexFile;  
                    	(($sHook = App::getHook($sHookName . 'IndexEnd')) ? eval($sHook) : false);
                        $sRes = $sPath.$sParam.'/index';
                    }
                }
            }
            elseif(file_exists(App::getParam('template', 'dir').$sPath.$sParam.'.html'))
            {
                //found template only (no page processing)
                $sRes = $sPath.$sParam;
            }
            else
            {
            	header("HTTP/1.0 404 Not Found");
              	$sRes = "public/error/404";
                if ( file_exists($sFullPath . 'site/public/_pre.php') )
                {
                	require_once $sFullPath . 'site/public/_pre.php';
                }
            }
        }

        return $sRes;
    }

    /** Correct user's url
     *
     * @access private
     * @param array $aAreas
     */
    function _correctUrl($aAreas)
    {
        static $bCorrected = false;
        if (! $bCorrected)
        {
      	if(strpos($_SERVER['PHP_SELF'],':'))
	       {
			App::gotoUrl('public');	        	
	       }
            if(10<strrpos($_SERVER['PHP_SELF'],'.'))
           	{
           		// Needed to support update from old versions (1.1 and lower)
				// This code corrects URLs like  "/index.php/poll.php/" or "/index.php/forum.php/" or "/index.php/blog.php/main/"
           		//$sPath = preg_replace ( '!/?index.php/([^.]*)(\.[^/]*)(.*)!', 'index.php/$1$3', $sPath );
           		$_SERVER['PHP_SELF'] = preg_replace( '!(/?index.php/[^.]*)(\.[^/]*)(.*)!', '$1$3', $_SERVER['PHP_SELF'] );
          	}
            $sPath = $_SERVER['PHP_SELF'];

            $sHost = App::getParam('host');
            $sSubFolder = substr($sHost, strpos($sHost, '/'));
            $aParts = explode('/', str_replace($sSubFolder, '/', $sPath));
            if (count($aParts) < 3)
            {
                $_SERVER['PHP_SELF'] = $sSubFolder.'index.php/'.current($aAreas);
            }
            else
            {
                if (!in_array($aParts[2], $aAreas))
                {
                    $_SERVER['PHP_SELF'] = $sSubFolder.'index.php/'.current($aAreas).substr($sPath, 10);
                }
            }
        }
    }


	/***********************
	*
	*	APPLICATION FLOW CONTROL
	*
	*****************************************************************/



    /**  Forward to specified phisical URL and add messages to session.
     * (add messages, sends header and call <tt>exit()</tt>).
     *
     * @see gotoUrl()
     * @see Template::addMes()
     *
     * @param string $sUrl      absolute URL to forward
     * @param mixed  $mMess     message or array of messages
     * @param string $sLogicUrl logical url corresponding to forwarder (For store messages)
     * @param string $sTarget   target error block name (by "_default")
     */
    function forward($sUrl, $mMess=array(), $sType='message', $sLogicUrl='', $sTarget='_default', $sExtra = '')
    {
        if (!is_array($mMess) && $mMess)
        {
            $mMess = array($mMess);
        }

        //correct last '/'
        if ('/' !== substr($sUrl, -1) &&
            '.html' !== substr($sUrl, -5) && '.php' !== substr($sUrl, -4) &&
            !strpos($sUrl, '#'))
        {
            $sUrl .= '/';
        }

        if (is_bool($sType))
        {
            $sType = $sType ? 'error' : 'message';
        }

        $sLogicUrl = $sLogicUrl ? $sLogicUrl : $sUrl;
        if ($mMess)
        {
            foreach($mMess as $sMess)
            {
                $_SESSION['_messages'][$sLogicUrl][$sTarget][$sMess] = array(
                    'text' => $sMess,
                    'type' => $sType,
                );
            }
        }
        if (stristr(PHP_OS, "win"))
        {
            session_write_close();
        }

		if ( $sExtra )
		{
			$sUrl = "". $sUrl ."#". $sExtra ."";
		}
		ob_clean();
        header('Location: '.$sUrl);
        exit;
    }

    /** Goto given url with stored back parameters (page, sorting etc)
     * @param string $sLogicUrl url name
     * @param mixed  $mMes     message(s) that should be displayed on target page
     * @param bool   $bErr      is error message(s)
     * @see setBackUrl()
     */
    function gotoBackUrl($sLogicUrl, $mMes=array(), $bErr = false)
    {
        App::forward(App::getBackUrl($sLogicUrl), $mMes, $bErr);
    }

    /**  Goto specified url.
     *
     * @param string $sUrlName  target url logic name (if empty - current url)
     * @param array  $aParams   additional params for url
     * @param mixed  $mMes      messages array
     * @param bool   $bErr      true - error messages, false - normal messages
     * @param string $sTarget   target error block name (by "_default")
     * @see forward()
     */
    function gotoUrl($sUrlName = '', $aParams = array(), $mMess=array(), $bErr=false, $sTarget='_default')
    {
        if ('' == $sUrlName)
        {
            App::gotoUrl(App::getPageName(), $aParams, $mMess, $bErr, $sTarget);
        }

        foreach ($aParams as $k=>$v)
        {
            if(is_int($k))
            {
                unset($aParams[$k]);
            }
        }
        App::forward(App::makeUrl($sUrlName, $aParams), $mMess, $bErr, $sUrlName, $sTarget);
    }

    function cleanUrl($sUrl, $bLangCharReplace = true)
    {   	
    	$sUrl = trim(strip_tags($sUrl));
		$sUrl = str_replace('"', '&quot;', $sUrl);
        $sUrl = str_replace('\'', '&#8217;', $sUrl);
        
		if ($bLangCharReplace)
		{
			$sUrl = strtr($sUrl, App::getParam('aLangCharReplace'));		
		}
		
		$sTagLink =$sUrl;

		if ($bLangCharReplace)
		{
			$sTagLink = preg_replace( '/ +/', '-',preg_replace('/[^0-9a-zA-Z$&;# ]+/', '-', $sTagLink));
		}
		
		$sTagLink = str_replace(' ', '-', $sTagLink);
		if (!$bLangCharReplace)
		{
			$sTagLink = rawurlencode(str_replace(' ', '-', $sTagLink));
		}

		$sTagLink = str_replace(array('-----', '----', '---', '--'), '-', $sTagLink);
		if (substr($sTagLink, -1) == '-')
		{
			$sTagLink = substr_replace($sTagLink, '', -1);
		}		
		
		return $sTagLink;
    }

    /** Set back url parameters for given logical url.
     * @param string $sUrlName logical URL name
     * @param Url    $oUrl     Url wrapper object
     * @see getBackUrl()
     * @see gotoBackUrl()
     */
    function setBackUrl($sUrlName)
    {
        $oUrl = &App::getUrl();
        $_SESSION['back_urls'][$sUrlName] = $oUrl->getParams();
        $_SESSION['back_urls']['_last'] = $sUrlName;
    }

    /** Get back url with parameters for given logical url.
     * @param string $sUrlName logical url name (or empty - for last back url)
     * @return string full url with stored parameters or triggers error
     * @see setBackUrl()
     */
    function getBackUrl($sUrlName='')
    {
        if (!$sUrlName && !isset($_SESSION['back_urls']['_last']))
        return App::getParam('url');

        $sUrlName = $sUrlName ? $sUrlName : $_SESSION['back_urls']['_last'];
        $aParams = array();
        if (isset($_SESSION['back_urls'][$sUrlName]))
        $aParams = $_SESSION['back_urls'][$sUrlName];
        return App::makeUrl($sUrlName, $aParams);
    }

    /** Get current page logic name
     *
     * @return string
     */
    function &getPageName()
    {
        static $sPageName = '';
        if ('' == $sPageName)
        {
            $oUrl = &App::getUrl();
            $aParams = $oUrl->getParams();
            foreach($aParams as $k=>$v)
            {
                if (!is_int($k))
                {
                    break;
                }
                $sPageName .= (($k > 0) ? '.' : '').$v;
            }
        }
        return $sPageName;
    }

    /** Set page name (if need to override automaticaly constructed page name)
     *
     * @see getPageName()
     */
    function setPageName($sPageName)
    {
        $sCurrPageName = &App::getPageName();
        $sCurrPageName = $sPageName;
    }

    /** Return messages for current (given) page
     *
     * @param string $sTarget
     * @param string $sPageName
     * @return unknown
     */
    function getPageMessages($sTarget='_default', $sPageName='')
    {
        $aMessages = array();

        return $aMessages;
    }

    /** Checks is given module exists in current application
     *
     * @param string $sModule module name
     * @return bool true - module exists, false - otherwise
     */
    function hasModule($sModule)
    {
        return App::loadClass('PhpFox_Mod_'.$sModule.'_Module');
    }

    // ========== DATABASE AND TABLE ==========
    /** Get table real name name
     *
     * @param string $sTable table name
     * @return string
     */
    function getT($sTable)
    {
		return App::getParam('db','prefix') . $sTable;
    }

    /** Returns full table info as array.
     *
     * @param string $sTable table code
     * @return array info on table (0 - real name, 1 - alias, 2 - PK)
     */
    function getTableInfo($sTable) {
        global $_TBL;
        return $_TBL[$sTable];
    }

    /** Get application template object.
     *
     * @return Template
     */
    function &getTemplate()
    {
        static $oTpl = null;

        if (null == $oTpl)
        {
            App::loadClass('Template');
            $oTpl = new Template();
        }
        return $oTpl;
    }

    function getLayout()
    {
    	if ( isset($_COOKIE['cssLayout']) )
    	{
    		return strip_tags($_COOKIE['cssLayout']);
    	}
    	return 'default';
    }

    function removeBrand()
    {
        if (file_exists(App::getParam('path').'include/settings/phpfox_brand.php'))
        {
            return false;
        }
        return true;
    }


	function checkUserAccess($sArea, $aPerm, $bExit = true)
	{
		$bIsAllowed = true;

    	$oSecurityService = &App::getModuleService('Account', 'Security');

    	if ( App::getSetting('section_'.$sArea) )
    	{
    		$bIsAllowed = false;
    	}
    	elseif ( !$oSecurityService->checkPerm($sArea, $aPerm, false) )
    	{
			$bIsAllowed = false;
		}

		if ( $sArea == 'video' && !App::getParam('useAjax') )
		{
			$bIsAllowed = false;
			$sType = 'param-userAjax';
		}

		if ( !$bIsAllowed )
		{
			if ( $bExit )
			{
				App::gotoUrl('public.account.membership', array('type' => (isset($sType) ? $sType : 'upgrade')));
			}
			else
			{
				return false;
			}
		}

		return true;
	}

	function getMemConfig($sPermCode)
	{
		$oSecurityService = &App::getModuleService('Account', 'Security');
		return $oSecurityService->getPermDetails($sPermCode);
	}

	function checkUserSize($bExit = true)
	{
		$oSecurityService = &App::getModuleService('Account', 'Security');
		$iMemMaxUpload = App::getData('max_upload');
		$oAccountService = &App::getModuleService('Account', 'Account');
		$iUsedSpace = $oAccountService->getUsedSpace($oSecurityService->getCurrentUserLogin());
        $iAllowedSpace = $oAccountService->getAllowedSpace($oSecurityService->getCurrentUser());
        $iMaxUploadSize = $iMemMaxUpload * 1024;
        if (($iAllowedSpace != 0) && (($iAllowedSpace - $iUsedSpace) < $iMaxUploadSize))
        {
            $iMaxUploadSize = $iAllowedSpace - $iUsedSpace;
        }

        if ( $bExit )
        {
        	if ( ($iMemMaxUpload != '0') && ($iMemMaxUpload < $iUsedSpace) )
        	{
				App::gotoUrl('public.account.membership', array('type' => 'filesize'), array('iMemMaxUpload' => $iMemMaxUpload, 'iMaxUploadSize' => $iMaxUploadSize));
			}
        }

		return array($iMemMaxUpload, $iUsedSpace, $iAllowedSpace, $iMaxUploadSize);
	}

	function updateUserSpace()
	{
		$oAccountService = &App::getModuleService('Account', 'Account');
		$oAccountService->getUsedSpace(App::getUser('user'), false, App::getUser('id'), true);
		return true;
	}

    function forceLogin()
    {
			 header("WWW-Authenticate: " .
        		"Basic realm=\"Admin Panel: " .
    	    	"Enter your username and password " .
	        	"for access.\"");
	        header("HTTP/1.0 401 Unauthorized");
	        print '<h1>Access Denied!</h1>';
	        exit;
    }

    function getData($sVar)
    {
    	static $aMem;
		if ( isset($aMem[$sVar]) )
		{
			return $aMem[$sVar];
		}
		$oSecurityService = &App::getModuleService('Account', 'Security');
		$aMem = $oSecurityService->getMembershipData(App::getUser('type'));
		return $aMem[$sVar];
    }

    function isStaff($bRedirect = false)
    {
    	if ( App::getUser('type') == '0' || App::getUser('type') == '1' )
    	{
    		return true;
    	}

    	if ( $bRedirect )
    	{
    		App::gotoUrl('public.denied');
    	}

    	return false;
    }

	/***********************
	*
	*	CACHE
	*
	*****************************************************************/

    function &getCache()
    {
        static $oCache = null;
        if (null == $oCache)
        {
            $oCache = App::newObject('Cache');
        }
        return $oCache;
    }

    function cacheData($sFile, $sQuery)
    {
		$oCache = &App::getCache();
		$oCache->setFile($sFile . '.php');
		if ( !$oCache->isCached() )
		{
			$oDb = &Database::get();
    		$aItem = $oDb->getRows($sQuery);
    		$oCache->save($aItem);
    	}
    	$aItems = $oCache->doRequire();
    	return $aItems;
    }

    function rmCache($sName)
    {
    	$oCache = &App::getCache();
    	$oCache->rmFile($sName);
    }

	/***********************
	*
	*	ERROR PROCESSING
	*
	*****************************************************************/

    /** * Add error(s) to application context.
     *
     * @param mixed $mErrors string or array of strings error(s)
     */
    function addErrors($mErrors)
    {
        $aErrors = &App::getErrors();
        if (is_array($mErrors))
        {
            foreach($mErrors as $sError)
            {
                $aErrors[] = $sError;
            }
        }
        else
        {
            $aErrors[] = $mError;
        }
    }

    /**  Get errors
     *
     * @return array error messages
     */
    function &getErrors()
    {
        static $aErrors = array();
        return $aErrors;
    }

    function _trigger_error($sError, $sFile, $sLine, $sErrorType = 'SCRIPT_ERROR', $bExit = false)
    {
    	switch($sErrorType)
    	{
    		case 'SCRIPT_ERROR':
			$sType = 'Script Error';
    		break;
    	}

    	$sStr = '<div style="padding:4px;">';
    	$sStr .= '<b>'. $sType . '</b>: ' . $sError;
    	if ( App::getParam('debug') )
    	{
    		$sStr .= '<br /><b>File:</b> '. str_replace(App::getParam('path'), '', $sFile) .'';
    		$sStr .= '<br /><b>Line:</b> '. $sLine .'';
		}
    	$sStr .= '</div>';
    	if ( $bExit )
    	{
			print $sStr;
			exit;
    	}
    	return $sStr;
    }

	/***********************
	*
	*	PLUGINS
	*
	*****************************************************************/

    function plugin_getForumThreads()
    {
        global $oPlugin;
        if (is_object($oPlugin))
        {
            return $oPlugin->phpfoxForumThreads();
        }
        return false;
    }
    function plugin_getForumTopics()
    {
        global $oPlugin;
        if (is_object($oPlugin))
        {
            return $oPlugin->phpfoxForumTopics();
        }
        return false;
    }
    function plugin_createUser($oAccount)
    {
        global $oPlugin;
        if (is_object($oPlugin))
        {
            $oPlugin->phpfoxCreateUser($oAccount);
        }
        return false;
    }
    function plugin_changePassword($oAccount)
    {
        global $oPlugin;
        if (is_object($oPlugin))
        {
            $oPlugin->phpfoxChangePassword($oAccount);
        }
        return false;
    }
    function plugin_loginUser($oAccount)
    {
        global $oPlugin;
        if (is_object($oPlugin))
        {
            $oPlugin->phpfoxLogin($oAccount);
        }
        return false;
    }
    function plugin_changeTheme($oAccount)
    {
        global $oPlugin;
        if (is_object($oPlugin))
        {
            $oPlugin->phpfoxCss($oAccount);
        }
        return false;
    }
    function plugin_logoutUser($oAccount)
    {
        global $oPlugin;
        if (is_object($oPlugin))
        {
            $oPlugin->phpfoxLogout($oAccount);
        }
        return false;
    }
    function plugin_updateAccount($oAccount)
    {
        global $oPlugin;
        if (is_object($oPlugin))
        {
            $oPlugin->phpfoxUpdateAccount($oAccount);
        }
        return false;
    }

    /** Checks that plugin with given name exists in phpfox installation
     *
     * @param unknown_type $sPluginName
     * @return unknown
     */
    function pluginInstalled($sPluginName)
    {
    	static $aCheck = array();

    	if ( isset($aCheck[$sPluginName]) )
    	{
    		return $aCheck[$sPluginName];
    	}

        $sFolderName = App::getParam('path').'plugins';
        $sFolderName .= '/'.$sPluginName.'/phpfox_functions.php';
        $aCheck[$sPluginName] = file_exists($sFolderName);

        return $aCheck[$sPluginName];
    }
    
    function getHook($sHook)
    {
    	return phpFoXPlugins::call($sHook);
    }

    /**
     * Checks if MP3 Plugin is installed
     *
     * @return boolean
     *
     */
    function isMp3PluginInstaled()
    {
        App::loadClass('Database');
        $oDb = Database::get();
        $aTable = $oDb->getRow('SHOW TABLES LIKE "' . App::getParam('plugin.mp3.tablename') . '"');
        return (App::pluginInstalled('mp3') && $aTable);
    }

	/***********************
	*
	*	SYSTEM and COMMAND LINE
	*
	*****************************************************************/

    /** Check that function with $sFunctionName is disabled
     *
     * @param string $sFunctionName function name
     * @return boolean
     */
    function _isFunctionDisabled($sFunctionName)
    {
        $sDisabledFunctions = @ini_get('disable_functions');
        if ($sDisabledFunctions)
        {
            $aFunctions = explode(',', $sDisabledFunctions);
            foreach ($aFunctions as $sFunction)
            {
                $aDisabledFunctions[$sFunction] = 'local';
            }
        }
        $sDisabledFunctions = get_cfg_var('disable_functions');
        if ($sDisabledFunctions)
        {
            $aFunctions = explode(',', $sDisabledFunctions);
            foreach ($aFunctions as $sFunction)
            {
                $aDisabledFunctions[$sFunction] = 'global';
            }
        }
        return isset($aDisabledFunctions[$sFunctionName]);
    }

    function devPrint($mStr, $bPrint_r = false)
    {
		ob_clean();

		if ( $bPrint_r )
		{
			print_r($mStr);
			exit;
		}

		print $mStr;
		exit;
    }

    /** Try to execute command by various methods and return executing result
     *
     * @param string $sCommand command
     * @return string
     */
    function executeCommand($sCommand)
    {
        static $aAllowedExecFunctions = null;
        if ($aAllowedExecFunctions === null)
        {
            $aExecFunctions = array
            (
                'shell_exec',
                'passthru',
                'system',
                'exec',
            );
            foreach ($aExecFunctions as $iKey => $sFunction)
            {
                if (App::_isFunctionDisabled($sFunction))
                {
                    unset($aExecFunctions[$iKey]);
                }
            }
            $aAllowedExecFunctions = $aExecFunctions;
        }
        $sReturn = false;
        if (!count($aAllowedExecFunctions))
        {
            return $sReturn;
        }
        $sFunction = current($aAllowedExecFunctions);
        switch ($sFunction)
        {
            case 'passthru':
                ob_start();
                $sFunction($sCommand);
                $sReturn = ob_get_contents();
                ob_end_clean();
                break;
            case 'shell_exec':
            case 'system':
            case 'exec':
                ob_start();
                $sReturn = $sFunction($sCommand);
                ob_end_clean();
                break;
        }
        return $sReturn;
    }

    function checkUploadParams($iSize)
    {
        if (!ini_get('file_uploads'))
        {
            return false;
        }

        $iPostMaxSize = App::_size2Byte(ini_get('post_max_size'));
        if ($iSize > $iPostMaxSize)
        {
            return false;
        }

        $iUploadMaxFileSize = App::_size2Byte(ini_get('upload_max_filesize'));
        if ($iSize > $iUploadMaxFileSize)
        {
            return false;
        }

        $iMaxInputTime = ini_get('max_input_time');
        if (($iMaxInputTime < 600) && ($iMaxInputTime != '-1'))
        {
            return false;
        }

        /*
        $iMemoryLimit = App::_size2Byte(ini_get('memory_limit'));
        if ($iSize > $iMemoryLimit and $iMemoryLimit != null)
        {
            return false;
        }
        */
        
        return true;
    }

    function _size2Byte($sVal)
    {
        if ($sVal)
        {
            $sVal = trim($sVal);
            $sLast = strtolower($sVal{strlen($sVal) - 1});
            switch($sLast)
            {
                case 'g':
                    $sVal *= 1024;
                case 'm':
                    $sVal *= 1024;
                case 'k':
                    $sVal *= 1024;
            }
        }
        return $sVal;
    }

	function convert_from_bytes( $bytes, $to=NULL )
	{
  		$float = floatval( $bytes );
  		switch( $to )
  		{
    		case 'Kb' :            // Kilobit
      		$float = ( $float*8 ) / 1024;
      		break;
    		case 'b' :             // bit
      		$float *= 8;
      		break;
    		case 'GB' :            // Gigabyte
      		$float /= 1024;
    		case 'MB' :            // Megabyte
      		$float /= 1024;
    		case 'KB' :            // Kilobyte
      		$float /= 1024;
    		default :              // byte
  		}
  		unset( $bytes, $to );
  		return( $float );
		}

    /**
     * Sets PHP_SELF and REQUEST_URI parameters depending on the server OS, and server settings.
     * Uses ?par on CGI (when $_CONF['path_translated'] is `false`).
     *
     * @return boolean
     *
     *
     *
     */
    function setServerParams()
    {
        $sPathTranslated = '';

        // if (!stristr(PHP_OS, "win") || !App::getParam('path_translated'))
        {
            if (isset($_GET[App::getParam('get_path_var')]) and $_GET[App::getParam('get_path_var')])
            {
                if (strpos($_GET[App::getParam('get_path_var')], '/index.php') !== 0)
                {
                    $sPathTranslated = '/index.php' . $_GET[App::getParam('get_path_var')];
                } else
                {
                    $sPathTranslated = $_GET[App::getParam('get_path_var')];
                }
            } elseif (isset($_POST[App::getParam('get_path_var')]) and $_POST[App::getParam('get_path_var')])
            {
                if (strpos($_POST[App::getParam('get_path_var')], '/index.php') !== 0)
                {
                    $sPathTranslated = '/index.php' . $_POST[App::getParam('get_path_var')];
                } else
                {
                    $sPathTranslated = $_POST[App::getParam('get_path_var')];
                }
            } else
            {
                $sPathTranslated = '/index.php/';
            }
        }
        /*
        elseif (isset($_SERVER['ORIG_PATH_INFO']))
        {
            $sPathTranslated = $_SERVER['ORIG_PATH_INFO'];
        }
        */

        /**
         * Fix for subfolder problem
         */
        if (strpos($sPathTranslated, '//') > 0)
        {
            $sPathTranslated = '/index.php/';
        }

        if ($sPathTranslated)
        {
            $_SERVER['PHP_SELF']    = $sPathTranslated;
            $_SERVER['REQUEST_URI'] = $sPathTranslated;
        }

        return true;
    }

	/***********************
	*
	*	JAVSCRIPT
	*
	*****************************************************************/

    /**
     * Makes Javascript with bIsPathTranslated variable definition
     *
     * @return string
     *
     *
     */
    function makeJSPathTranslatedValue()
    {
    	$oLang =& App::getLanguage();
    	
        $sVal = App::getParam('path_translated') ? 'true' : 'false';
        $sHtml  = '<script type="text/javascript">' . "\n";
        $sHtml .= "\t\t" . 'var bIsPathTranslated = ' . $sVal . ';' . "\n";
        $sHtml .= "\t\t" . 'var sGetPathVar = "' . App::getParam('get_path_var') . '";' . "\n";
        $sHtml .= "\t\t" . 'var sHome = "' . App::getParam('url') . '";' . "\n";
        $sHtml .= "\t\t" . 'var sLangVar = "' . (file_exists(App::getParam('path') . 'design/tiny_mce/langs/' . $oLang->aLanguage['languagecode'] . '.js') ? $oLang->aLanguage['languagecode'] : 'en') . '"; '. "\n";
        $sHtml .= "\t\t" . 'var bDoGzip = ' . (App::getParam('use_gzip') ? 'true' : 'false') . ';' . "\n";
        $sHtml .= "\t\t" . 'var sUsVarId = "' . App::getParam('us_var_id') . '";' . "\n";
        $sHtml .= "\t\t" . 'var sUsName = "' . App::format('Mod_Language.united_states') . '";' . "\n";
		$sHtml .= "\t\t" . "var msg = new Array(9);\n";
		$sHtml .= "\t\t" . "msg[0] = '". str_replace("'", "\'", App::format('javascript_delete_item')) ."'\n";
		$sHtml .= "\t\t" . "msg[1] = '". str_replace("'", "\'", App::format('problem_year')) ."';\n";
		$sHtml .= "\t\t" . "msg[2] = '". str_replace("'", "\'", App::format('problem_month')) ."';\n";
		$sHtml .= "\t\t" . "msg[3] = '". str_replace("'", "\'", App::format('problem_data')) ."';\n";
		$sHtml .= "\t\t" . "msg[4] = '". str_replace("'", "\'", App::format('incorrect_date_format')) ."';\n";
		$sHtml .= "\t\t" . "msg[5] = '". str_replace("'", "\'", App::format('gecko_users')) ."';\n";
		$sHtml .= "\t\t" . "msg[6] = '". str_replace("'", "\'", App::format('opera_users')) ."';\n";
		$sHtml .= "\t\t" . "msg[7] = '". str_replace("'", "\'", App::format('browser_bookmark')) ."';\n";
		$sHtml .= "\t\t" . "msg[8] = '". str_replace("'", "\'", App::format('Mod_Site.please_select_item')) ."';\n\t";		
        $sHtml .= '</script>';
        return $sHtml;
    }

    function loadAjax($aModules, $aFunctions, $bTinyMce = false)
    {
		if ( !App::getParam('useAjax') )
		{
			return;
		}

    	$oUrl = &App::getUrl();

    	if ( !is_array($aFunctions) )
    	{
    		$aFunctions = array($aFunctions);
    	}

    	if ( !is_array($aModules) )
    	{
    		$aModules = array($aModules);
    	}
    	
    	(($sHook = App::getHook(__CLASS__ . __FUNCTION__)) ? eval($sHook) : false);

    	foreach($aModules as $sModule)
    	{
    		$sAjaxFile = App::getParam('path') . "include/modules/". $sModule ."/functions/Ajax.functions.php";
			if ( file_exists($sAjaxFile) )
			{
				require_once $sAjaxFile;
			}
		}

		require_once App::getParam('path') . "include/functions/Ajax.functions.php";

		$oXajax = new xajax($oUrl->getUrl());
		if (App::getParam('debug.ajax'))
		{
			$oXajax->debugOn();
		}
		$oXajax->bWaitCursor = false;
		foreach($aFunctions as $aFunction)
		{
			if (empty($aFunction)) 
			{
				continue;
			}
			$oXajax->registerFunction($aFunction);
		}
		$oXajax->processRequests();


	    $oTpl = &App::getTemplate();
	    $oTpl->assign(array
	    (
		   	'scriptaculous' => (!$bTinyMce ? true : false),
		   	'lightbox' => false,
    		'xajax' => App::getParam('useAjax') ? $oXajax->getJavascript(App::getParam('url').'design/js') : '',
			'turnOnMCE' => (!$bTinyMce ? true : false)
    	));
    }

    function getAjax($aFunctions)
    {
    	$oUrl = &App::getUrl();

    	if ( !is_array($aFunctions) )
    	{
    		$aFunctions = array($aFunctions);
    	}

		require_once App::getParam('path') . "include/functions/Ajax.functions.php";
		$oXajax = new xajax($oUrl->getUrl());
		foreach($aFunctions as $aFunction)
		{
			$oXajax->registerFunction($aFunction);
		}
		$oXajax->processRequests();

		return $oXajax->getJavascript(App::getParam('url').'design/js');
    }
    
	/***********************
	*
	*	SESSIONS
	*
	*****************************************************************/

    function getSession($sName)
    {
    	if ( isset($_SESSION[$sName]) )
    	{
    		return $_SESSION[$sName];
    	}
    	return '';
    }

    function setSession($sName,$sValue)
    {
    	$_SESSION[$sName] = $sValue;
    }

    function unsetSession($sName)
    {
    	unset($_SESSION[$sName]);
    }
    
	function getAccessForContent($sModule, $sFile, $sType)
    {
    	$sModule = strtolower($sModule); 
    	$aAccessStore = isset($_SESSION['aAccessStore'])? $_SESSION['aAccessStore']:array();
    	if(!isset($aAccessStore[$sModule][$sFile]))
    	{
    		$bAccess = App::checkUserAccess($sModule, array('read_only','full'), false);
			$bSpecialCheck = TRUE;

			if($bAccess)
			{
				$sModuleName= ucwords($sModule);
				$sSrv = App::getModuleService($sModuleName,$sModuleName);
				if(method_exists($sSrv, 'getAccessForContent'))
				{
					$bSpecialCheck = $sSrv->getAccessForContent($sFile);
				}
			}
    		
    		$aAccessStore[$sModule][$sFile] = ($bAccess AND $bSpecialCheck);
    	}
    	$_SESSION['aAccessStore'] = $aAccessStore;
    	return $aAccessStore[$sModule][$sFile];
    }
    
    function setAccessForContent($sModule, $sFile)
    {
    	$sModule = strtolower($sModule); 
    	$aAccessStore = (isset($_SESSION['aAccessStore']) ? $_SESSION['aAccessStore'] : array());
    	$aAccessStore[$sModule][$sFile] = 1;
    	$_SESSION['aAccessStore'] = $aAccessStore;
    	return true;
    }
    
    function clearAccessForContent($sModule)
    {
    	$sModule = strtolower($sModule);
    	if(isset($_SESSION['aAccessStore'][$sModule]))
    		unset($_SESSION['aAccessStore'][$sModule]);
    	return true;
    }
}
?>